package com.bootdo.clouddo.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.utils.R;
import com.bootdo.clouddo.utils.StringUtils;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/36kr")
public class B36KrApiController {

    private static final String video_url = "https://36kr.com/pp/api/info-flow/channel_video/videos";

    @GetMapping("/videos")
    public R getVideos(String per_page, String b_id) {
        try {
            JSONObject resultVo = sendGetRequest(video_url + "?per_page=" + per_page + "&b_id=" + b_id);
            if(resultVo != null) {
                return R.data(resultVo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }


    private static JSONObject sendGetRequest(String url) {
        Map<String, String> params = new HashMap<>();
        return sendGetRequest(url, params, null);
    }

    private static JSONObject sendGetRequest(String url, Map<String, String> params) {
        return sendGetRequest(url, params, null);
    }

    private static JSONObject sendGetRequest(String url, Map<String, String> params, String token){
        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        if(StringUtils.isNotBlank(token)) {
            headers.add("Authorization", "Bearer "+token);
        }
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(params, headers);

        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<JSONObject> response = client.exchange(url, method, requestEntity, JSONObject.class);

        return response.getBody();
    }
}
